﻿#include "TheilSenRegression.h"
#include <QVector>
#include <vector>

bool TheilSenRegression::fit(double x[], double y[], int n)
{
    m_k = 0;
    std::vector<double> temp;
    for(int i = 0; i < n; i++)
    {
        for(int j = i + 1; j < n; j++)
        {
            double det_x = x[i] - x[j];
            if(fabs(det_x) < 1e-6) continue;
            temp.push_back( (y[i] - y[j]) / (det_x) );
        }
    }

    std::sort(temp.begin(), temp.end());
    m_k = temp[temp.size() / 2];
    temp.clear();
    for(int i = 0; i < n; i++)
    {
        temp.push_back(y[i] - m_k * x[i]);
    }
    std::sort(temp.begin(), temp.end());

    m_b = temp[temp.size() / 2];
    return true;
}
